<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2017/8/24  19:25
 */
namespace app\admin\controller;
use think\Request;
use think\Db;

class Withdrawals extends Common
{


    public function index()
    {
        $where=array();
        $status=input('status');
        if($status!=''){
            $where['w.status'] =$status;
        }
        $keyword=input('keyword');
        if($keyword!=''){
            $where['w.bank|s.shopname|s.realname|w.name|w.mobile|w.branch'] =array("like",'%'.$keyword.'%');
        }
        $starttime=trim(input('starttime'));
        if(!empty($starttime)){//全部订单
            $where['w.create_time'] =array("gt",strtotime($starttime));
        }
        $endtime=trim(input('endtime'));
        if(!empty($starttime)){//全部订单
            $where['w.create_time'] =array("gt",strtotime($endtime));
        }
        if(!empty($starttime) && !empty($endtime)){//全部订单
            $where['w.create_time'] =array("between",[strtotime($starttime),strtotime($endtime)]);
        }
        if(input('export')){
            $this->export($where);exit;
        }
        $list = db("withdrawals")->alias("w")
            ->field("w.*,s.shopname,s.realname")
            ->join("shop s","w.shop_id=s.id")
            ->where($where)
            ->order("w.id desc")
            ->paginate(5);
        //var_dump($list);exit;
  /*      $list->each(function($i){
            $i['order_goods']=db("order_goods")->where("order_id=".$i['id'])->select();
            return $i;
        });*/
        $count =  db("withdrawals")->alias("w")
            ->field("s.*,s.shopname,s.realname")
            ->join("shop s","w.shop_id=s.id")
            ->where($where)
            ->order("w.id desc")
            ->count();
        $this->assign("list",$list);
        $this->assign("count",$count);
        $this->assign("status",$status);
        $this->assign("keyword",$keyword);
        $this->assign("starttime",$starttime);
        $this->assign("endtime",$endtime);
        return $this->fetch();
    }
    /**
     * 订单列表导出excel
     */
    public function export($where)
    {

        $headArr = array("id","商户店名","商户法人","联系号码","所属银行","开户分行","银行卡号","持卡人","提现金额","手续费",
            '应打款','状态',"申请时间","审核时间");
        $data=array();
        $list = db("withdrawals")->alias("w")
            ->field("w.*,s.shopname,s.realname")
            ->join("shop s","w.shop_id=s.id")
            ->where($where)
            ->order("w.id desc")
            ->select();
        foreach($list as $k => $v){
            $data[$k][] = $v['id'];
            $data[$k][] = $v['shopname'];
            $data[$k][] = $v['realname'];
            $data[$k][] = $v['mobile'];
            $data[$k][] = $v['bank'];
            $data[$k][] = $v['branch'];
            $data[$k][] = $v['card_num'];
            $data[$k][] = $v['name'];
            $data[$k][] = $v['money'];
            $data[$k][] = $v['poundage'];
            $data[$k][] = $v['paid'];
            switch($v['status']){
                case '0': $data[$k][]='待审核';break;
                case '1': $data[$k][]='已打款';break;
                case '-1': $data[$k][]='不通过';break;
            }
            $data[$k][] = date("Y-m-d H:i",$v['create_time']);
            $data[$k][] =!empty($v['check_time'])?date("Y-m-d H:i",$v['check_time']):'';
        }
        $filename='提现列表-'.date("Y-m-d h:i:s");
        (new Export())->ImportExcel($filename,$headArr,$data);
    }
    /**
    * 审核
    */
    public function check(){
        $id = input('id/d');
        $status = input('status/d');
        $withdrawals=db("withdrawals")->where("id='$id'")->find();
        if(!in_array($status,array(1,-1))){
            return $this->error('审核状态有误');
        }
        if($withdrawals['status']!=0){
            return $this->error('不能重复审核');
        }

        if($status==1) {
            $result = $this->send($withdrawals['card_num'],$withdrawals['name'],$withdrawals['paid']);
            if(isset($result['TRANSRET'])){
                if($result['TRANSRET']['RET_CODE'] != 0000) {
                    if(is_string($result))$this->error($result);
                    if(isset($result['INFO']['ERR_MSG']))$this->error($result['INFO']['ERR_MSG']);
                }
            }else{
                if(is_string($result))$this->error($result);
                if(isset($result['INFO']['ERR_MSG']))$this->error($result['INFO']['ERR_MSG']);
            }
            $data['req_sn'] = $result['INFO']['REQ_SN'];
            $data['status']=1;
            $data['check_time']=time();
            $res = db("withdrawals")->where("id='$id'")->update($data);
            if(!$res)$this->error('系统繁忙，稍后再试');
        }
        if($status==-1){
            $data['status']=-1;
            $res = db("withdrawals")->where("id='$id'")->update($data);
            if(!$res) $this->error('系统繁忙，稍后再试');
            $plus=db("shop")->where("id=".$withdrawals['shop_id'])->setInc("balance",$withdrawals['money']);
            if(!$plus) $this->error('返还余额失败');
        }
        $this->success('发起提现成功，请等待到账!');
    }

    /**
    * 会员提现审核
    *
    */
    public function member_check(){
        $id = input('id/d');
        $status = input('status/d');
        $withdrawals=db("member_withdrawals")->where("id='$id'")->find();
        if(!in_array($status,array(1,-1))){
            $this->error('审核状态有误');
        }
        if($withdrawals['status']!=0){
            $this->error('不能重复审核');
        }
        
        if($status==1) {
            $result = $this->send($withdrawals['card_num'],$withdrawals['name'],$withdrawals['paid']);
            if(isset($result['TRANSRET'])){
                if($result['TRANSRET']['RET_CODE'] != 0000) {
                    if(is_string($result))$this->error($result);
                    if(isset($result['INFO']['ERR_MSG']))$this->error($result['INFO']['ERR_MSG']);
                }
            }else{
                if(is_string($result))return $this->error($result);
                if(isset($result['INFO']['ERR_MSG'])){
                    $this->error($result['INFO']['ERR_MSG']);
                }
            }

            $data['req_sn'] = $result['INFO']['REQ_SN'];
            $data['status']=1;
            $data['check_time']=time();
            $res = db("member_withdrawals")->where("id='$id'")->update($data);
            if(!$res) $this->error('系统繁忙，稍后再试');
        }
        if($status==-1){
            $data['status']=-1;
            $res = db("member_withdrawals")->where("id='$id'")->update($data);
            if(!$res) $this->error('系统繁忙，稍后再试');
        }
        $this->success('发起提现成功，请等待到账!');
    }

    //交易查询
    public function transaction_query(){
        $transaction_query = input('transaction_query');

        $result = $this->query($transaction_query);
        var_dump($result);die;
        $this->success($result);
    }

    /**
    * 打款
    */
    public function send($acc_no,$acc_name,$money){
        header('Content-Type: text/html; Charset=UTF-8');

        vendor('allinwithdraw.PhpTools');

        $tools= new \PhpTools();
        //var_dump($this->generateOrderNo());die;
        // 源数组
        $params = array(
            'INFO' => array(
                'TRX_CODE' => '100014',
                'VERSION' => '03',
                'DATA_TYPE' => '2',
                'LEVEL' => '6',
                'USER_NAME' => '20058100001497304',
                'USER_PASS' => '111111',
                'REQ_SN' => '200581000014973-'.$this->generateOrderNo(),
            ),
            'TRANS' => array(
                'BUSINESS_CODE' => '09900',
                'MERCHANT_ID' => '200581000014973',
                'SUBMIT_TIME' => date('YmdHis',time()),
                'BANK_CODE' => '0105',
                'ACCOUNT_TYPE' => '00',
                'ACCOUNT_NO' => "$acc_no",
                'ACCOUNT_NAME' => "$acc_name",
                'ACCOUNT_PROP' => '0',
                'AMOUNT' => $money*100,
                'CURRENCY' => 'CNY',
                'ID_TYPE' => '0',
                'CUST_USERID' => '2901347',
                'SUMMARY' => '商户提现',
                'REMARK' => '30238924-1984857237-237843',
            ),
        );

        //发起请求
        $result = $tools->send($params);
        //var_dump($result);die;
        if($result!=FALSE){
            return $result['AIPG'];
        }else{
            return "验签结果：验签失败，请检查通联公钥证书是否正确";
        }
    }

    /**
    * 交易查询
    */
    public function query($req_sn){
        header('Content-Type: text/html; Charset=UTF-8');

        vendor('allinwithdraw.PhpTools');

        $tools= new \PhpTools();
        
        // 源数组
        $params = array(
            'INFO' => array(
                'TRX_CODE' => '200004',
                'VERSION' => '03',
                'DATA_TYPE' => '2',
                'LEVEL' => '6',
                'USER_NAME' => '20058100001497304',
                'USER_PASS' => '111111',
                'REQ_SN' => '200581000014973-'.$this->generateOrderNo(),
            ),
            'QTRANSREQ' => array(
            'QUERY_SN' => $req_sn,
            'MERCHANT_ID' => '200581000014973',
            'STATUS' => '2',
            'TYPE' => '2',
            'START_DAY' => '',
            'END_DAY' => ''
            ),
        );

        //发起请求
        $result = $tools->send($params);
        //var_dump($result);die;
        if($result!=FALSE){
            return $result['AIPG'];
        }else{
            return "验签结果：验签失败，请检查通联公钥证书是否正确";
        }
    }

    //生成唯一标识
    public function generateOrderNo()
    {
        $yearCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn =
            $yearCode[intval(date('Y')) - 2017] . strtoupper(dechex(date('m'))) . date(
                'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 999));
        return $orderSn;
    }

    /**
     * 司机提现审核
     *
     */
    public function driver_check(){
        $id = input('id/d');
        $status = input('status/d');
        $withdrawals=db("driver_withdrawals")->where("id='$id'")->find();
        if(!in_array($status,array(1,-1))){
            $this->error('审核状态有误');
        }
        if($withdrawals['status']!=0){
            $this->error('不能重复审核');
        }

        if($status==1) {
            $result = $this->send($withdrawals['card_num'],$withdrawals['name'],$withdrawals['paid']);
            if(isset($result['TRANSRET'])){
                if($result['TRANSRET']['RET_CODE'] != 0000) {
                    if(is_string($result))$this->error($result);
                    if(isset($result['INFO']['ERR_MSG']))$this->error($result['INFO']['ERR_MSG']);
                }
            }else{
                if(is_string($result))return $this->error($result);
                if(isset($result['INFO']['ERR_MSG'])){
                    $this->error($result['INFO']['ERR_MSG']);
                }
            }

            $data['req_sn'] = $result['INFO']['REQ_SN'];
            $data['status']=1;
            $data['check_time']=time();
            $res = db("driver_withdrawals")->where("id='$id'")->update($data);
            if(!$res) $this->error('系统繁忙，稍后再试');
        }
        if($status==-1){
            $data['status']=-1;
            $res = db("driver_withdrawals")->where("id='$id'")->update($data);
            if(!$res) $this->error('系统繁忙，稍后再试');
        }
        $this->success('发起提现成功，请等待到账!');
    }
}
